using System;
using System.Net.Http;

namespace K3Cloud.WebApi.Core.IoC.Http;

/// <summary>
/// HttpClient 工厂，用于创建和配置 HttpClient 实例
/// </summary>
public static class HttpClientFactory
{
    /// <summary>
    /// 默认超时时间（秒）
    /// </summary>
    public static int DefaultTimeoutSeconds { get; set; } = 100;

    /// <summary>
    /// 是否启用连接池（默认启用）
    /// </summary>
    public static bool EnableConnectionPool { get; set; } = true;

    /// <summary>
    /// 是否启用自动解压缩（默认启用）
    /// </summary>
    public static bool EnableDecompression { get; set; } = true;

    /// <summary>
    /// 创建 HttpClient 实例
    /// 如果启用了连接池，则从连接池获取；否则创建新实例
    /// </summary>
    /// <param name="baseUrl">服务器基础地址</param>
    /// <param name="timeoutSeconds">超时时间（秒），如果为 null 则使用默认值</param>
    /// <returns>HttpClient 实例</returns>
    public static System.Net.Http.HttpClient CreateClient(string baseUrl, int? timeoutSeconds = null)
    {
        var timeout = TimeSpan.FromSeconds(timeoutSeconds ?? DefaultTimeoutSeconds);

        if (EnableConnectionPool)
        {
            // 从连接池获取
            return HttpClientPool.Instance.GetOrCreate(baseUrl, timeout);
        }
        else
        {
            // 创建新实例（向后兼容模式）
            return CreateNewClient(baseUrl, timeout);
        }
    }

    /// <summary>
    /// 创建新的 HttpClient 实例（不使用连接池）
    /// </summary>
    /// <param name="baseUrl">服务器基础地址</param>
    /// <param name="timeout">超时时间</param>
    /// <returns>HttpClient 实例</returns>
    private static System.Net.Http.HttpClient CreateNewClient(string baseUrl, TimeSpan timeout)
    {
        var handler = new HttpClientHandler();

        if (EnableDecompression)
        {
            handler.AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate;
        }

        var client = new System.Net.Http.HttpClient(handler)
        {
            BaseAddress = new Uri(baseUrl),
            Timeout = timeout
        };

        client.DefaultRequestHeaders.Add("User-Agent", "K3Cloud.WebApi.Core.IoC/1.2");

        return client;
    }

    /// <summary>
    /// 清空连接池
    /// </summary>
    public static void ClearPool()
    {
        if (EnableConnectionPool)
        {
            HttpClientPool.Instance.Clear();
        }
    }

    /// <summary>
    /// 获取连接池统计信息
    /// </summary>
    public static string GetPoolStats()
    {
        if (EnableConnectionPool)
        {
            return $"连接池状态: 已启用, 当前连接数: {HttpClientPool.Instance.Count}";
        }
        else
        {
            return "连接池状态: 已禁用";
        }
    }
}
